package com.hbut.friend.service.exam.imp;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hbut.common.core.constants.Constants;
import com.hbut.common.core.domain.TableDataInfo;
import com.hbut.common.core.utils.ThreadLocalUtil;
import com.hbut.friend.domain.exam.dto.ExamQueryDTO;
import com.hbut.friend.domain.exam.vo.ExamVO;
import com.hbut.friend.manager.ExamCacheManager;
import com.hbut.friend.mapper.exam.ExamMapper;
import com.hbut.friend.service.exam.IExamService;
import io.jsonwebtoken.lang.Collections;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
@RefreshScope
public class ExamServiceImp implements IExamService {
    @Autowired
    private ExamMapper examMapper;

    @Autowired
    ExamCacheManager examCacheManager;

    @Override
    public List<ExamVO> list(ExamQueryDTO questionQueryDTO) {
        PageHelper.startPage(questionQueryDTO.getPageNum(), questionQueryDTO.getPageSize());
        return examMapper.selectExamList(questionQueryDTO);
    }

    @Override
    public TableDataInfo redisList(ExamQueryDTO questionQueryDTO) {
        //从redis中获取 竞赛列表的数据
        Long userId = null;
        Long total = examCacheManager.getListSize(questionQueryDTO.getType(),userId);
        List<ExamVO> examVOList;
        // 如果redis中没有数据或者数据量为0
        if(total == null || total <= 0){
            // 从数据库中获取竞赛列表
            examVOList = examMapper.selectExamList(questionQueryDTO);
            //将数据存入redis中
            examCacheManager.refreshCache(questionQueryDTO.getType(),userId);
        }else{
            // 从redis中获取竞赛列表
            examVOList = examCacheManager.getExamVOList(questionQueryDTO,userId);
            // 更新总数
            total = new PageInfo<>(examVOList).getTotal();
        }
        // 如果竞赛列表为空
        if(Collections.isEmpty(examVOList)){
            return TableDataInfo.empty();
        }
        assembleExamVOList(examVOList);
        // 返回竞赛列表和总数
        return TableDataInfo.success(examVOList, total);
    }

    private void assembleExamVOList(List<ExamVO> examVOList) {
        Long userId = ThreadLocalUtil.get(Constants.USER_ID, Long.class);
        List<Long> userExamIdList = examCacheManager.getAllUserExamList(userId);
        if(Collections.isEmpty(userExamIdList)){
            return;
        }
        for(ExamVO examVO : examVOList){
            if(userExamIdList.contains(examVO.getExamId())){
                examVO.setEnter(true);
            }
        }
    }


}
